class InitView extends BaseView {



    //滚动的字幕数组
    private captionPool: egret.TextField[] = [];
    //字幕的数据源
    private captionData: any[] = [];
    //字幕显示开关
    private showCaption: boolean = true;

    constructor() {
        super();
        this.initView();
    }


    private captionSprite: egret.Sprite = null;
    private initRotation: number = 0;
    private bombMc: egret.MovieClip = null;
    private shadowMc: egret.MovieClip = null;
    private remainCount: number = 0;
    private currentScore: number = 0;
    private maxRotation: number = 18;

    private async initView() {
        let bg: egret.Bitmap = utils.createBitmapByName('bg');
        bg.width = this.width;
        bg.height = this.height;
        this.addChild(bg);

        let user = await this.checkUserType();
        this.captionSprite = utils.createSprite({
            width: this.width
        });
        this.addChild(this.captionSprite);

        let rotation = Math.random() * this.maxRotation;
        this.initRotation = Math.random() < 0.5 ? rotation : -rotation;


        await this.createBp();

        if (GameData.is_tiyan) {
            // 游客模式初始化
            this.guestInit();
        } else {
            // 正常情况下初始化
            this.createSubViews(); //一行三个
            this.getHome();
        }
        //获取字典
        CurlUtil.curl(config.api_url + '/bxg/config').then((data: any) => {
            if (data.code == 200) {
                GameData.maxScore = data.data.max_add_score;
                GameData.personalRank = data.data.personal_rank;
                GameData.gangRank = data.data.gang_rank;
                GameData.resetSeed = data.data.top_up_seed;
                this.maxText.text = GameData.maxScore + '';
                this.luanchComplete = true;
            } else {
                Main._parent.addChild(NoticeView.getInstance());
                NoticeView.getInstance().noticeMsg = "获取字典信息失败!";
                NoticeView.getInstance().noticetitle = '提示';
                NoticeView.getInstance().callback = function () {
                    tvm.closeH5();
                };
            }
        }).catch((e) => {
            Main._parent.addChild(NoticeView.getInstance());
            NoticeView.getInstance().noticeMsg = "网络请求异常!";
            NoticeView.getInstance().noticetitle = '提示';
            NoticeView.getInstance().callback = function () {
                tvm.closeH5();
            };
        });

        this.bombMc = await ViewManager.mcManager.play('bomb', 'bomb', 'bomb');
        this.shadowMc = await ViewManager.mcManager.play('shadow', 'shadow', 'shadow');
        this.bombMc.addEventListener(egret.Event.COMPLETE, this.bombComplete, this);
        this.shadowMc.addEventListener(egret.Event.COMPLETE, this.shadowComplete, this);
        this.shadowMc.scaleX = 2;
        this.shadowMc.scaleY = 1.2;
    }

    // 游客模式初始化
    private guestInit() {
        // 容错处理 
        if (!GameData.is_tiyan) return;
        var self = this;
        // 游客模式 分数从缓存中取
        //   this.currentScore = Number(wx.getStorageSync('guestScore')) || 0;
        this.currentScore = Number(utils.getCookie('guestScore')) || 0;
        this.scoreText.text = this.currentScore + '';
        // 游客恢复现场
        CurlUtil.curl(config.api_url + '/bxg/guest_home').then(function (data) {
            if (data['status'] == 'success') {
                data = data['data'];
                GameData.share_reset_count = data['share_reset_count'] || 0;
                GameData.video_reset_count = data['video_reset_count'] || 0;
                // 剩余次数分别从缓存和接口中取 取较大值
                //   var storageRemainCount = Number(wx.getStorageSync('guestRemainCount')) || 0;
                var storageRemainCount = Number(utils.getCookie('guestRemainCount')) || 0;
                var remainCount = data['remain_count'] || 0;
                self.remainCount = Math.max(remainCount, storageRemainCount);
                self.countText.text = self.remainCount + '';
            } else {
                GameData.hasBeginning = false;
                self.gameOver();
            }
        });

        // 开始游戏
        this.startGame();
        this.createMonstor('daiji');
    }


    public getHome() {
        if (GameData.is_tiyan == true) return;
        CurlUtil.curl(config.api_url + '/bxg/home', {}).then((data: any) => {
            if (data['status'] == "success") {
                GameData.share_reset_count = data['data']['share_reset_count'];
                GameData.video_reset_count = data['data']['video_reset_count'];
                data['data']['start_remain_time'] = 10;
                this.refreshMyData(data['data']);
                this.refreshCountDown(data['data']);
            } else if (data['code'] == 3001) {
                GameData.hasBeginning = false;
                this.gameOver();
                this.showRankView(data);
            }
        })
    }

    private notbegin: egret.Bitmap;
    public gameOver() {
        this.notbegin = utils.createBitmapByName('mupai');
        this.notbegin.width = 369;
        this.notbegin.height = 360;
        this.notbegin.x = this.width / 2 - this.notbegin.width / 2;
        this.notbegin.y = this.height / 2 - this.notbegin.height / 2 + 100;
        this.addChildAt(this.notbegin, this.getChildIndex(this.cannon) - 1);
        if (this.monstorMc && this.contains(this.monstorMc)) {
            this.removeChild(this.monstorMc);
            this.monstorMc.stop();
        }
        //停止游戏
        this.stopGame();
        if (GameData.is_tiyan) return;
        CurlUtil.curl(config.api_url + '/bxg/rank/personal/last', {}).then((data: any) => {
            if (data.status == 'success') {
                //上期排行揭晓
                if (data.data.list.length <= 0) {
                    Main.showNoEndView();
                } else {
                    Main.showLastJFView();
                }
                //上期帮派
                CurlUtil.curl(config.api_url + '/bxg/rank/gang/last', {}).then((result: any) => {
                    if (result.status == 'success') {
                        var o = {
                            'personal_rank': data.data.list,
                            'gang_rank': result.data.list,
                        }

                        this.showRankView(o);

                    }
                })
            } else {
                Main._parent.addChild(NoticeView.getInstance());
                NoticeView.getInstance().noticeMsg = "上期排行榜获取失败!【" + data.code + "】";
            }
        }).catch((e) => {
            Main._parent.addChild(NoticeView.getInstance());
            NoticeView.getInstance().noticeMsg = "接口异常！";
        });

    }


    private showRankView(data) {
        if (this.rankView && this.contains(this.rankView)) {
            this.removeChild(this.rankView);
        }
        this.rankView = new RankView(data);
        this.rankView.width = 218;
        this.rankView.height = this.rankView.width / 218 * 321;
        this.rankView.y = this.propAwardView.y;
        this.rankView.x = GameData.stageW - this.rankView.width - 5;
        this.addChild(this.rankView);
    }
    private refreshCountDown(data) {//刷新倒计时和积分排行榜
        this.showRankView(data);
        if (data['start_remain_time']) {//游戏还未开始，进入游戏倒计时已经结束，无法继续游戏
            GameData.hasBeginning = false;
            this.gameOver();
            if (data['start_remain_time'] < 86400) { //倒计时在一天之内 显示开始倒计时
                this.showCountDown(data['start_remain_time'], false);
            }
            return;
        }
        if (this.notbegin && this.contains(this.notbegin)) {
            this.removeChild(this.notbegin);
        }
        GameData.hasBeginning = true;
        //获取弹幕
        CurlUtil.curl(config.api_url + '/bxg/barrage', { count: 20 }).then((data: any) => {
            if (data.code = 200 && Array.isArray(data.data)) {
                for (let i = 0, len = data.data.length; i < len; i++) {
                    this.captionData.push(data.data.pop());
                }
            }
        }).catch(function () {
            console.log('调用弹幕接口失败')
        });
        GameData.lefTime = data['remain_time'];
        this.showCountDown(data['remain_time'], true);
        this.createMonstor('daiji');
        //开始游戏
        this.startGame();
    }

    private showCountDown(time, beginning: boolean = false) {
        if (!this.countdownView) {
            this.countdownView = new CountDownView();
            this.countdownView.y = this.propAwardView.y + 10;
            this.countdownView.width = 274;
            this.countdownView.height = this.countdownView.width / 274 * 83;
            this.addChild(this.countdownView);
            this.countdownView.x = (this.rankView.x - utils.getMaxX(this.propAwardView) - this.countdownView.width) / 2 + utils.getMaxX(this.propAwardView);
        }
        this.countdownView.refreshTime(time, beginning);
    }

    private refreshMyData(data: any) {
        if (GameData.is_tiyan) {
            this.countText.visible = false;
            this.scoreText.visible = false;
        } else {
            if (data['start_remain_time']) {
                this.countText.text = '';
                this.scoreText.text = '';
            } else {
                this.remainCount = data.remain_count || 0;
                this.currentScore = data.score || 0;
                this.countText.text = this.remainCount + '';
                this.scoreText.text = this.currentScore + '';
            }

        }

    }
    private propAwardView: PropAwardView;
    public countdownView: CountDownView;
    private rankView: RankView;
    private helpImg: egret.Bitmap;
    private createSubViews() {
        if (!GameData.is_tiyan) {
            this.propAwardView = new PropAwardView();
            this.propAwardView.y = 120;
            this.propAwardView.x = 20;
            this.propAwardView.width = 150;
            this.propAwardView.height = this.propAwardView.width / 150 * 122;
            this.addChild(this.propAwardView);

            this.helpImg = utils.createBitmapByName('help');
            this.helpImg.width = 80;
            this.helpImg.height = 82;
            this.helpImg.x = 55;
            this.helpImg.y = utils.getMaxY(this.propAwardView) + 10;
            this.helpImg.touchEnabled = true;
            this.helpImg.addEventListener(egret.TouchEvent.TOUCH_TAP, this.showHelp, this);
            this.addChild(this.helpImg);
        }
    }

    private showHelp() {
        Main.showHelpView();
    }
    private monstorMc: any;
    private jifenView: JifenView;
    private createMonstor(jsonName: string, times: number = -1, score: number = 0) {
        var self = this;
        return new Promise(async (reslove, reject) => {
            if (self.monstorMc && self.contains(self.monstorMc)) {
                self.removeChild(self.monstorMc);
                self.monstorMc.stop();
            }
            this.monstorMc = await ViewManager.mcManager.play(jsonName, jsonName, jsonName);
            this.monstorMc.scaleX = this.monstorMc.scaleY = 1.5;
            this.monstorMc.x = GameData.stageW / 2 - this.monstorMc.scaleX * 400 / 2;
            this.monstorMc.y = GameData.stageH / 2 - 230;
            this.monstorMc.gotoAndPlay(0, times);
            if (times != -1) {
                this.monstorMc.once(egret.Event.COMPLETE, reslove, this);
            }
            this.addChild(this.monstorMc);
            this.setChildIndex(this.monstorMc, 2);
            if (jsonName == 'daiji') {
                return;
            }
            this.jifenView = new JifenView(score);
            this.jifenView.jifenType = jsonName;
            this.jifenView.width = 375 * 0.9;
            this.jifenView.height = this.jifenView.width / 375 * 258;
            this.jifenView.anchorOffsetX = this.jifenView.width / 2;
            this.jifenView.anchorOffsetY = this.jifenView.height / 2;
            this.jifenView.x = GameData.stageW / 2;
            this.jifenView.y = this.monstorMc.y - this.jifenView.height / 2 + 160;
            this.addChild(this.jifenView);
            if (jsonName == 'baoji') {
                this.jifenView.scaleX = 0;
                this.jifenView.scaleY = 0;
                egret.Tween.get(this.jifenView).to({ scaleX: 1, scaleY: 1 }, 200, egret.Ease.backOut);
            }
        });
    }




    private playBombMc(): void {
        if (this.bombMc) {
            this.bombMc.x = this.indicator.x + (this.indicator.height) * Math.sin(Math.PI / 180 * this.indicator.rotation);
            this.bombMc.y = this.indicator.y - (this.indicator.height) * Math.cos(Math.PI / 180 * this.indicator.rotation);
            this.addChild(this.bombMc);
            this.bombMc.gotoAndPlay(0, 1)
        }
    }
    private playShadowMc(): void {
        if (this.shadowMc) {
            this.shadowMc.x = this.indicator.x;
            this.shadowMc.y = this.indicator.y;
            this.shadowMc.rotation = this.indicator.rotation;
            this.addChild(this.shadowMc);
            this.addChildAt(this.shadowMc, this.getChildIndex(this.kd) + 1);
            this.shadowMc.gotoAndPlay(0, 1);
        }
    }
    private bombComplete(): void {
        if (this.contains(this.bombMc)) {
            this.removeChild(this.bombMc);
        }
    }
    private shadowComplete(): void {
        if (this.contains(this.shadowMc)) {
            this.removeChild(this.shadowMc);
        }
    }




    //指针
    private indicator: egret.Bitmap = null;
    private cannon: egret.MovieClip = null;
    private kd: egret.Bitmap = null;
    private bp: egret.Bitmap = null;
    private kp: egret.Bitmap = null;
    private scoreText: egret.TextField = null;
    private countText: egret.TextField = null;
    private maxText: egret.TextField = null;
    private leftText: egret.TextField = null;
    private rightText: egret.TextField = null;
    private scroll: egret.ScrollView = null;
    private async createBp() {

        //表盘背景
        let bp: egret.Bitmap = utils.createBitmapByName('bp');
        bp.x = this.width / 2 - bp.width / 2;
        bp.y = this.height - bp.height;

        //大炮
        var mc = await ViewManager.mcManager.play('launch', 'launch', 'launch');
        mc.x = GameData.stageW / 2;
        mc.y = bp.y + 30;
        this.addChild(mc);
        //播放完成时停留在第一帧
        mc.addEventListener(egret.Event.COMPLETE, () => {
            mc.gotoAndStop(0)
        }, this);
        this.cannon = mc;
        this.setChildIndex(this.cannon, 100);

        this.addChild(bp);
        this.bp = bp;
        //刻度
        let kd_bg: egret.Bitmap = utils.createBitmapByName('kd');
        let scroll = new egret.ScrollView();
        scroll.width = kd_bg.width;
        scroll.height = kd_bg.height - 10;
        scroll.anchorOffsetX = scroll.width / 2;
        scroll.x = this.width / 2;
        scroll.y = this.height - scroll.height - bp.height * 0.2 - 15;
        scroll.horizontalScrollPolicy = 'off';
        scroll.verticalScrollPolicy = 'off';
        this.addChild(scroll);
        this.scroll = scroll;
        scroll.setContent(kd_bg);


        let kd: egret.Bitmap = utils.createBitmapByName('kd_score', { offsetX: 0.5, offsetY: 1 });
        kd.x = scroll.x;
        kd.y = scroll.y + kd.height;
        kd.rotation = this.initRotation;
        this.kd = kd;
        this.addChild(kd);

        //开炮按钮
        let kp: TbitMap = utils.createBitmapByName('kp', {
            offsetX: 0.5,
            offsetY: 0.5
        });
        kp.x = this.width / 2;
        kp.y = this.height - kp.height / 2;
        //指针
        let indicator: egret.Bitmap = utils.createBitmapByName('indicator', {
            offsetX: 0.5,
            offsetY: 1
        });
        indicator.x = scroll.x;
        indicator.y = kp.y;
        this.addChild(indicator);
        this.indicator = indicator;

        this.addChild(kp);
        kp.touchAnimation = true;
        kp.addEventListener(egret.TouchEvent.TOUCH_TAP, this.luanch, this);
        // <begin>
        // if (GameData.is_tiyan) {
        //     // 发送消息给开放数据域
        //     var platform = window.platform;
        //     if (!this.bitmap && !this.contains(this.bitmap)) {
        //         this.bitmap = platform.openDataContext.createDisplayObject(null, this.stage.stageWidth, this.stage.stageHeight);
        //         this.addChild(this.bitmap);
        //     }
        //     // 显示排行榜
        //     window.platform.openDataContext.postMessage({
        //         command: "open"
        //     });
        // }
        // </begin>
        this.kp = kp;
        //刻度提示
        let maxText: egret.TextField = utils.createTextField({
            text: '0',
            width: 200,
            size: 22,
            textColor: 0xFDDC22,
            bold: true
        });
        maxText.anchorOffsetX = maxText.width / 2;
        maxText.anchorOffsetY = maxText.height / 2;
        maxText.x = this.width / 2 + (kd.width / 2 - 40) * Math.sin(Math.PI / 180 * this.initRotation);
        maxText.y = scroll.y + scroll.height - (kd.width / 2 - 40) * Math.cos(Math.PI / 180 * this.initRotation);
        this.addChild(maxText);
        this.maxText = maxText;

        //刻度提示
        let leftText: egret.TextField = utils.createTextField({
            text: '0',
            size: 22,
            textColor: 0xFDDC22,
            bold: true
        });
        leftText.anchorOffsetX = leftText.width / 2;
        leftText.x = scroll.x - scroll.width / 2 + 30;
        leftText.y = this.height - leftText.height - 68;
        this.addChild(leftText);
        this.leftText = leftText;
        //刻度提示
        let rightText: egret.TextField = utils.createTextField({
            text: '0',
            size: 22,
            textColor: 0xFDDC22,
            bold: true
        });
        rightText.anchorOffsetX = rightText.width / 2;
        rightText.x = scroll.x + scroll.width / 2 - 30;
        rightText.y = this.height - rightText.height - 68;
        this.addChild(rightText);
        this.rightText = rightText;

        //当前积分
        let score_text: egret.TextField = utils.createTextField({
            text: '',
            width: 180,
            height: 40,
            size: 28,
            textColor: 0xFDDC22,
            bold: true
        });
        score_text.x = bp.x + 40;
        score_text.y = this.height - score_text.height - 20;
        this.addChild(score_text);
        this.scoreText = score_text;
        //次数
        let count_text: egret.TextField = utils.createTextField({
            text: '',
            width: 180,
            height: 40,
            size: 28,
            textColor: 0xFDDC22,
            bold: true
        });
        count_text.x = bp.x + bp.width - 40 - count_text.width;
        count_text.y = this.height - count_text.height - 20;
        this.addChild(count_text);
        this.countText = count_text;
        this.stopGame();

        // <begin> -- forWX
        // if (GameData.is_tiyan) {
        //     // 发送消息给开放数据域
        //     var platform = window.platform;
        //     if (!this.bitmap && !this.contains(this.bitmap)) {
        //         this.bitmap = platform.openDataContext.createDisplayObject(null, this.stage.stageWidth, this.stage.stageHeight);
        //         this.addChild(this.bitmap);
        //     }
        //     // 显示排行榜
        //     window.platform.openDataContext.postMessage({
        //         command: "open"
        //     });
        // }
        // 授权登录
        // var _this = this;
        // wx.getSetting({
        //     success(res) {
        //         if (res.authSetting['scope.userInfo']) {
        //             // 已经授权，可以直接调用
        //             _this.checkUserInfo(function () {
        //                 _this.luanch();
        //             });
        //         } else {
        //             // 未授权 弹出授权框
        //             _this.checkUserInfo();
        //         }
        //     }
        // });
        // </begin>
    }

    private userInfoBtn: any;
    private checkUserInfo(cb): void {
        // <begin>
        //  // 1.微信登录授权
        // if (!user_info) {
        //   var self = this;
        //   var kp = this.kp;
        //   if (!this.userInfoBtn) {
        //     var userInfoBtn = wx.createUserInfoButton({
        //       type: "text",
        //       text: "",
        //       style: {
        //         left: kp.x / 2 - kp.anchorOffsetX / 2,
        //         top: kp.y / 2 - kp.anchorOffsetY / 2,
        //         width: kp.width / 2,
        //         height: kp.height / 2,
        //         lineHeight: 40,
        //         backgroundColor: '',
        //         color: '#ffffff',
        //         textAlign: 'center',
        //         fontSize: 16,
        //         borderRadius: 4
        //       }
        //     });
        //     self.userInfoBtn = userInfoBtn;
        //     userInfoBtn.onTap((res) => {
        //       try {
        //         user_info = res.userInfo;
        //         if (user_info == undefined) {
        //           return;
        //         }
        //         userInfoBtn.destroy();
        //         if (cb) cb();
        //       } catch (err) {
        //         user_info = undefined;
        //       }
        //     });
        //   }
        //   return;
        // }
        // </begin>
    }

    private changeBpRotation(): void {
        let rotation = Math.random() * this.maxRotation;;
        this.initRotation = Math.random() < 0.5 ? rotation : -rotation;
        this.kd.rotation = this.initRotation;
        this.maxText.x = this.width / 2 + (this.kd.width / 2 - 40) * Math.sin(Math.PI / 180 * this.initRotation);
        this.maxText.y = this.scroll.y + this.scroll.height - (this.kd.width / 2 - 40) * Math.cos(Math.PI / 180 * this.initRotation);
    }


    //指针摆动
    private rotateIndicator() {
        let rotation = this.indicator.rotation;
        let speed = GameData.rotateSpeed / 180;
        let firstTime = (90 - rotation) * speed;
        egret.Tween.get(this.indicator, { loop: true }).to({ rotation: 90 }, firstTime).to({ rotation: -90 }, GameData.rotateSpeed).to({ rotation: rotation }, GameData.rotateSpeed - firstTime);
    }
    //指针停止摆动
    private stopRotateIndicator(homeing: boolean = true) {
        egret.Tween.removeTweens(this.indicator);
        if (homeing) {
            this.indicator.rotation = 0;
        }
    }

    private luanchComplete: boolean = false;

    /**
     * 发射
     */
    private luanch(): void {
        if (!this.luanchComplete || !GameData.hasBeginning) return;//gamedata.hasbeginning 是否在活动中，不在活动中，不能点击
        var self = this;
        if (GameData.is_tiyan) {
            // 1.减次数
            if (this.remainCount-- > 0) {
                this.countText.text = this.remainCount + '';
                this.luanchComplete = false;
                this.stopRotateIndicator(false);
                //指针动画
                this.playBombMc();
                this.playShadowMc();

                //获取开炮结果
                var rotation = this.indicator.rotation;
                if (rotation / this.initRotation) { }
                // 调接口
                utils.checkGuestResult(this.initRotation, rotation).then(function (data: any) {
                    if (data.code == 200) {
                        self.playLuanchMc(data.b, data.score);
                    }
                }).catch(function (data) {
                    if (data.code == 5004) {
                        Toast.makeText({ text: "您的次数用完了，请明天再来!" }).show();
                        self.countText.text = '0';
                        utils.setCookie('guestRemainCount', self.countText.text);
                    }
                    else {
                        Main._parent.addChild(NoticeView.getInstance());
                        NoticeView.getInstance().noticeMsg = "接口异常，请稍后再试!";
                    }
                });
            } else {
                // Toast.makeText({ text: "您的次数用完了，请明天再来!" }).show();
                this.resetCount();
            }
        }
        else {
            if (this.remainCount-- > 0) {
                this.countText.text = this.remainCount + '';
                this.luanchComplete = false;
                this.stopRotateIndicator(false);
                //指针动画
                this.playBombMc();
                this.playShadowMc();
                //获取开炮结果
                let rotation = this.indicator.rotation;
                utils.checkResult(this.initRotation, rotation).then((data: any) => {
                    if (data.code == 200) {
                        this.playLuanchMc(data.b, data.score);
                        this.captionData.push({ nickname: user_info.nickname, score: data.score });
                    }
                }).catch(function (data: any) {
                    if (data.code == 5004) {
                        Toast.makeText({ text: "您的次数用完了，请下期再来!" }).show();
                    } else {
                        Main._parent.addChild(NoticeView.getInstance());
                        NoticeView.getInstance().noticeMsg = "接口异常，请稍后再试!";
                    }
                });
            } else {
                this.resetCount();
            }
        }
    }

    /** 重置次数  */
    private resetCount(): void {
        var type = 1;
        var self = this;
        // 优先看能不能看视频重置 
        if (GameData.video_reset_count > 0) {
            type = 3;
        } else if (GameData.share_reset_count > 0) {
            type = 2;
        }
        // 如果是游客 并且不能视频重置和分享重置了 那么直接弹提示明天再来
        if (GameData.is_tiyan && type == 1) {
            Toast.makeText({ text: "您的次数用完了，请明天再来!" }).show();
            return;
        }
        Main.showResetView(type).then(function () {
            switch (type) {
                case 1:
                    if (!GameData.is_tiyan) {
                        self.goldhomeRest(type);
                    } else {
                        Toast.makeText({ text: "您还没有种子，请下载电视红包App！" }).show();
                    }
                    break;
                case 2:
                    // <begin> --forWX
                    // wx.shareAppMessage({
                    //     title: '分享title',
                    //     success: function () {
                    //         // 转发成功 
                    //         if (!GameData.is_tiyan) {
                    //             self.goldhomeRest(type);
                    //         } else {
                    //             self.guestRest(type);
                    //         }
                    //     }
                    // });
                    // </begin>
                    break;
                case 3:
                    // <begin> --forWX
                    // wx.shareAppMessage({
                    //     title: '看视频啊',
                    //     success: function () {
                    //         // 转发成功 
                    //         if (!GameData.is_tiyan) {
                    //             self.goldhomeRest(type);
                    //         } else {
                    //             self.guestRest(type);
                    //         }
                    //     }
                    // });
                    // </begin>
                    break;
            }
            Main.removeResetView();
        }).catch(function () {
            Main.removeResetView();
        });
    }

    /**家园用户重置 */
    private goldhomeRest(type: number) {
        var self = this;
        CurlUtil.curl(config.api_url + '/bxg/reset').then(function (res: any) {
            if (res.code == 200) {
                if (type == 2) {
                    GameData.share_reset_count--;
                } else if (type == 3) {
                    GameData.video_reset_count--;
                }
                self.remainCount = res.data.max_count;
                self.currentScore = 0;
                self.countText.text = self.remainCount + '';
                self.scoreText.text = self.currentScore + '';
                Toast.makeText({ text: '重置成功' }).show();
                self.getHome();
            }
            else if (res.code == 604) {
                Toast.makeText({ text: "种子不足" }).show();
            }
            else if (res.code == 605) {
                Toast.makeText({ text: "扣除种子失败" }).show();
            }
            else {
                Toast.makeText({ text: "重置失败，请稍后再试" }).show();
            }
        }).catch(function () { });
    }

    /**游客重置接口 type 2是分享 3是视频 */
    private guestRest(type: number) {
        let self = this;
        if (type == 1) { // 种子先待定
            return;
        }
        CurlUtil.curl(config.api_url + '/bxg/guest_reset', { type: type }).then(function (res: any) {
            if (res.code == 200) {
                if (type == 2) {
                    GameData.share_reset_count--;
                } else if (type == 3) {
                    GameData.video_reset_count--;
                }
                self.remainCount = res.data.max_count;
                self.currentScore = 0;
                self.countText.text = self.remainCount + '';
                self.scoreText.text = self.currentScore + '';
                Toast.makeText({ text: '重置成功' }).show();
                // 重置本地数据
                utils.setCookie("guestScore", self.scoreText.text);
                utils.setCookie('guestRemainCount', self.countText.text);
            } else {
                switch (res.code) {
                    case 9006:
                        Toast.makeText({ text: "视频重置机会已用完，请明天再试!" }).show();
                        GameData.video_reset_count = 0;
                        break;
                    default:
                        Toast.makeText({ text: "重置失败，请稍后再试" }).show();
                        break;
                }
            }
        }).catch(function () { });
    }


    //开始游戏
    private startGame(): void {
        this.kp.texture = RES.getRes('kp');
        this.kp.touchEnabled = true;
        this.bp.texture = RES.getRes('bp');
        this.indicator.visible = true;
        this.maxText.visible = true;
        this.leftText.visible = true;
        this.rightText.visible = true;
        this.kd.visible = true;
        this.rotateIndicator();
    }

    //停止游戏
    private stopGame(): void {
        this.kp.texture = RES.getRes('kp_black');
        this.kp.touchEnabled = false;
        this.bp.texture = RES.getRes('bp_black');
        this.kd.visible = false;
        this.maxText.visible = false;
        this.leftText.visible = false;
        this.rightText.visible = false;
        this.indicator.visible = false;
        this.scoreText.text = '';
        this.countText.text = '';
        this
        this.stopRotateIndicator();
    }


    /**
     * 播放发射动画
     */
    private playLuanchMc(isBaoji: boolean, score: number) {
        this.cannon.gotoAndPlay(0, 1);
        let jsonName: string = 'attack';
        if (isBaoji) {
            jsonName = 'baoji';
        }
        setTimeout(async () => {
            await this.createMonstor(jsonName, 1, score);
            //加分
            var self = this;
            this.currentScore += score;
            this.scoreText.text = this.currentScore + '';
            // 游客模式 分数和次数存本地缓存
            if (GameData.is_tiyan) {
                utils.setCookie('guestScore', self.scoreText.text);
                utils.setCookie('guestRemainCount', self.countText.text);
                // 如果次数用完了 发送到排行榜 并更新排行榜数据
                if (self.remainCount == 0) {
                    // <begin> --forWX
                    // wx.setUserCloudStorage({
                    //     KVDataList: [{ key: 'score', value: self.scoreText.text }],
                    //     success: res => {
                    //         // 让子域更新当前用户的最高分，因为主域无法得到getUserCloadStorage;
                    //         // 更新完分数再刷新排行榜
                    //         window.platform.openDataContext.postMessage({
                    //             command: "update"
                    //         });
                    //     },
                    //     fail: res => {
                    //         console.log("fail" + res);
                    //     }
                    // });
                    // </begin>
                }
            } else {
                this.rankView.refreshRank(this.currentScore);
            }
            if (jsonName == 'baoji') {

                if (this.jifenView && this.contains(this.jifenView)) {
                    egret.Tween.get(this.jifenView).to({ scaleX: 0, scaleY: 0 }, 200, egret.Ease.backIn).call(function () {
                        this.removeChild(this.jifenView);
                        this.jifenView = null;
                        this.restart();
                    }.bind(this));
                }
            } else if (jsonName == 'attack') {
                if (this.jifenView && this.contains(this.jifenView)) {
                    egret.Tween.get(this.jifenView).to({ y: GameData.stageH / 2 - 230 - 258 * 0.9 + 130, alpha: 0 }, 300).call(function () {
                        this.removeChild(this.jifenView);
                        this.jifenView = null;
                    }.bind(this));
                    this.restart();
                }
            }
        }, 900);
    }

    private restart() {
        if (!GameData.hasBeginning) {
            ViewManager.initView.gameOver();
            return;
        }
        this.createMonstor('daiji');
        this.luanchComplete = true;
        this.changeBpRotation();
        this.rotateIndicator();
        if (this.remainCount <= 0) {
            this.resetCount();
        }
    }


    private getCaptionItem(content: string, color: number): egret.TextField {
        let caption: egret.TextField = null;
        if (this.captionPool.length > 0) {
            caption = this.captionPool.pop();
        } else {
            caption = utils.createTextField({
                size: 28,
                height: 40
            });
        }
        caption.text = content;
        caption.textColor = color;
        return caption;
    }



    private checkUserType() {
        return new Promise((reslove, reject) => {
            if (true) {
                reslove();
            }
        });
    }



    private lastCaptionPosition: number = 0;
    private firstLast: egret.TextField = null;
    private secondLast: egret.TextField = null;
    private thirdLast: egret.TextField = null;

    public update(): void {
        if (this.showCaption && this.captionData.length > 0) {
            let data = this.captionData.shift();
            let content = utils.getChar(data.nickname, 30) + '获得了' + data.score + '积分';
            let caption = this.getCaptionItem(content, utils.getRandomColor());
            caption.y = caption.height * this.lastCaptionPosition++;
            if (this.lastCaptionPosition == 1) {
                caption.x = this.firstLast ? Math.max(GameData.stageW, this.firstLast.x + this.firstLast.width + 50) : GameData.stageW;
                this.firstLast = caption;
            } else if (this.lastCaptionPosition == 2) {
                caption.x = this.secondLast ? Math.max(GameData.stageW, this.secondLast.x + this.secondLast.width + 50) : GameData.stageW;
                this.secondLast = caption;
            } else if (this.lastCaptionPosition == 3) {
                caption.x = this.thirdLast ? Math.max(GameData.stageW, this.thirdLast.x + this.thirdLast.width + 50) : GameData.stageW;
                this.thirdLast = caption;
            }

            this.lastCaptionPosition = this.lastCaptionPosition > 2 ? 0 : this.lastCaptionPosition;
            this.captionSprite.addChild(caption);
            egret.Tween.get(caption).to({ x: -caption.width }, 8000).call(() => {
                this.captionSprite.removeChild(caption);
                this.captionData.push(data);
                this.captionPool.push(caption);
                data = null;
            });
        }
    }
}